import Vue from 'vue'
import axios from 'axios'
import store from '@/store'
import router from '@/router'
import { Loading, Message } from 'element-ui'
import _ from 'lodash'
let loadingInstance = null // 加载动画实例
let reqId = 0 // 请求id
let reqId1 = 0 // 请求id
// 加载动画开启
function loadingInstanceOpen() {
  loadingInstance = Loading.service({
    fullscreen: true,
    background: 'rgba(255,255,255,0.2)'
  })
}
// 加载动画关闭
function loadingInstanceClose() {
  setTimeout(() => {
    if (loadingInstance) loadingInstance.close()
    loadingInstance = null
  }, 0)
}

function messageOpen(message) {
  Message({
    offset: 100,
    showClose: true,
    type: 'error',
    message: message
  })
}

// 创建 axios 实例
const request = axios.create({
  baseURL: process.env.VUE_APP_RemoteUrl,
  timeout: 60000,
  headers: { 'Content-Type': 'application/json;charset=utf-8' }
})

// 添加请求拦截器
request.interceptors.request.use(
  function (config) {
    if (config.isLoading !== false) {
      if (!loadingInstance) loadingInstanceOpen()
      Object.assign(config, { myReqId: ++reqId })
    }
    if (config.isAuthorization !== false) {
      Object.assign(config.headers, { authorization: store.getters?.getAuthorization || '' })
    }

    return config
  },
  function (error) {
    // 对请求错误做些什么
    loadingInstanceClose()
    return Promise.reject(error)
  }
)

// 添加响应拦截器
request.interceptors.response.use(
  function (response) {
    if (response.config.isLoading !== false) {
      if (response.config.myReqId === reqId) loadingInstanceClose()
    }
    // 对响应数据做点什么
    return response.data
  },
  function (error) {
    // 对响应错误做点什么
    if (error?.config?.myReqId === reqId) {
      if (error?.response?.data?.code === 401) {
        messageOpen('身份无效，请重新登录！')
        let fullPath = router.currentRoute.fullPath
        console.log(fullPath)
        // 重定向到登录页
        store.commit('setPropertyGeneral', {
          key: 'authorization',
          value: ''
        })
        store.commit('setUser', { phone: null })
        router.replace({
          path: '/',
          query: { redirect: fullPath }
        })
      } else {
        messageOpen(error.message || '网络错误，请检查您的网络！')
      }

      if (error?.config?.isLoading !== false) {
        loadingInstanceClose()
      }
    }

    return Promise.reject(error)
  }
)

const request1 = axios.create({
  baseURL: process.env.VUE_APP_RemoteUrl,
  timeout: 60000,
  headers: { 'Content-Type': 'application/json;charset=utf-8' }
})

// 添加请求拦截器
request1.interceptors.request.use(
  function (config) {
    if (_.get(config.headers, 'defaultHeader', true)) {
      _.assign(config.headers, {
        'Content-Type': _.get(config.headers, 'Content-Type', 'application/json')
      })
      if (store.getters?.getAuthorization)
        _.assign(config.headers, {
          authorization: _.get(
            config.headers,
            'authorization',
            store.getters?.getAuthorization || ''
          )
        })
    }

    delete config.headers.defaultHeader
    Object.assign(config, { myReqId: ++reqId1 })
    return config
  },
  function (error) {
    // 对请求错误做些什么
    // loadingInstanceClose()
    return Promise.reject(error)
  }
)

// 添加响应拦截器
request1.interceptors.response.use(
  function (response) {
    // 对响应数据做点什么
    if (response.headers.authorization) {
      store.commit('setPropertyGeneral', {
        key: 'authorization',
        value: response.headers.authorization
      })
    }

    return response
  },
  function (error) {
    // 对响应错误做点什么
    if (error?.response?.data?.code === 401) {
      messageOpen('身份无效，请重新登录！')

      let fullPath = router.currentRoute.fullPath
      console.log(fullPath)
      // 重定向到登录页
      store.commit('setPropertyGeneral', {
        key: 'authorization',
        value: ''
      })
      store.commit('setUser', { phone: null })
      router.replace({
        path: '/',
        query: { redirect: fullPath }
      })

    } else {
      messageOpen(error.message || '网络错误，请检查您的网络！')
    }
    return Promise.reject(error)
  }
)

export { request, request1 }
